package com.rzgeo.workmap;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.ActionMode;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;

import com.esri.arcgisruntime.geometry.Point;
import com.esri.arcgisruntime.layers.FeatureLayer;
import com.esri.arcgisruntime.layers.Layer;
import com.esri.arcgisruntime.mapping.view.DefaultMapViewOnTouchListener;
import com.esri.arcgisruntime.mapping.view.MapView;
import com.rzgeo.rzmaplib.RmlFeatureLayerQueryHelper;
import com.rzgeo.rzmaplib.action.RmlFreeDrawAction;
import com.rzgeo.rzmaplib.action.RmlGeoEditAction;
import com.rzgeo.rzmaplib.action.RmlMarkPolygonDrawAction;
import com.rzgeo.rzmaplib.comp.RmlFeatureInfo;
import com.rzgeo.rzmaplib.comp.RmlLayerList;
import com.rzgeo.rzmaplib.comp.RmlPanel;
import com.rzgeo.rzmaplib.comp.RmlTaskList;
import com.rzgeo.rzmaplib.comp.geoview.RmlMapViewHolder;
import com.rzgeo.rzmaplib.model.RmlEnv;
import com.rzgeo.rzmaplib.model.RmlPrj;
import com.rzgeo.rzmaplib.model.RmlPrjMapLoader;
import com.rzgeo.rzmaplib.util.IRmlLoadListener;
import com.rzgeo.rzmaplib.util.IRmlSerializable;
import com.rzgeo.rzmaplib.util.RmlUtil;

import java.util.ArrayList;

public class DroneMapActv extends AppCompatActivity {

    private static final int START_ACTION_IMAGE_CAPTURE = 12224;
    private RmlMapViewHolder _geoViewHolder;
    private RmlPrjMapLoader _mapLoader;
    private RmlLayerList _layerList;
    private RmlPanel _leftPanel;
    private RmlPanel _rightPanel;
    private RmlFeatureInfo _featureInfo;
    private Toolbar _toolbar;
    private RmlTaskList _tasklist;
    private View _fl_drone_panel;
    private View _rl_map_panel;
    private View _btn_max_drone_panel;
    private View _btn_max_map_panel;


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

//        if(START_ACTION_IMAGE_CAPTURE==requestCode){
//            _takePhotoHandler.postResultIntent(data);
//        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        /**标题是属于View的，所以窗口所有的修饰部分被隐藏后标题依然有效,需要去掉标题**/
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        StartInfo info =
                (StartInfo) getIntent().getSerializableExtra(StartInfo.Key);
        RmlPrj prj = RmlEnv.getInstance().getAppDir().prjsSet.getPrj(info.prjName);

        setContentView(R.layout.actv_map_drone);

        _toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(_toolbar);

        _btn_max_map_panel =findViewById(R.id.btn_max_map_panel);
        _btn_max_drone_panel =findViewById(R.id.btn_max_drone_panel);

        _fl_drone_panel=findViewById(R.id.fl_drone_panel);
        _rl_map_panel=findViewById(R.id.rl_map_panel);

        _geoViewHolder = new RmlMapViewHolder((MapView) findViewById(R.id.mapview));

        _layerList = findViewById(R.id.layerlist);

        _featureInfo = findViewById(R.id.featureinfo);
        _tasklist=findViewById(R.id.tasklist);

        _leftPanel = findViewById(R.id.panel_left);
        _leftPanel.setup(findViewById(R.id.btn_closeleft));
        _rightPanel = findViewById(R.id.panel_right);
        _rightPanel.setup(findViewById(R.id.btn_closeright));

        _mapLoader = new RmlPrjMapLoader(this, prj, _geoViewHolder, new IRmlLoadListener() {
            @Override
            public void Loaded(boolean success, String msg) {
                _layerList.setMapModel(DroneMapActv.this, _geoViewHolder, null, null);
            }
        });


        View.OnClickListener onMaxSwitchClick=new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(view==_btn_max_map_panel){
                    _btn_max_map_panel.setVisibility(View.GONE);
                    _btn_max_drone_panel.setVisibility(View.VISIBLE);
                    _fl_drone_panel.bringToFront();
                }else{
                    _btn_max_drone_panel.setVisibility(View.GONE);
                    _btn_max_map_panel.setVisibility(View.VISIBLE);
                    _rl_map_panel.bringToFront();
                }

//                float z1 = _btn_max_map_panel.getZ();
//                float z2 = _btn_max_drone_panel.getZ();
//                _btn_max_map_panel.setZ(z1);
//                _btn_max_drone_panel.setZ(z2);

                ViewGroup.LayoutParams lpDrone = _fl_drone_panel.getLayoutParams();
                ViewGroup.LayoutParams lpMap = _rl_map_panel.getLayoutParams();

                lpDrone.width=_rl_map_panel.getWidth();
                lpDrone.height=_rl_map_panel.getHeight();

                lpMap.width=_fl_drone_panel.getWidth();
                lpMap.height=_fl_drone_panel.getHeight();

                _fl_drone_panel.setLayoutParams(lpDrone);
                _rl_map_panel.setLayoutParams(lpMap);
            }
        };
        _btn_max_map_panel.setOnClickListener(onMaxSwitchClick);
        _btn_max_drone_panel.setOnClickListener(onMaxSwitchClick);
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {

            new AlertDialog.Builder(this)
                    .setTitle("是否离开项目")
                    .setPositiveButton("离开", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    })
                    .setNegativeButton("留下", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    }).show();
            return true;//不执行父类点击事件
        }
        return super.onKeyDown(keyCode, event);//继续执行父类其他点击事件
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        _mapLoader.release();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.actv_map, menu);

        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int viewId = -1;

        if (item.getItemId() == R.id.act_geoedit) {
            final MapView mv = (MapView) _geoViewHolder.getGeoView();
            final ArrayList<FeatureLayer>fl2Edit=new ArrayList<>();
            ArrayList<String>fl2EditTitles=new ArrayList<>();
            for(FeatureLayer l:_mapLoader.getPrj().getOptionalMap().getLayers()){
                if(l.getFeatureTable()!=null
                        &&l.getFeatureTable().isEditable()
                        &&l.isVisible()
                ){
                    fl2Edit.add(l);
                    fl2EditTitles.add(l.getName());
                }
            }
            if(fl2Edit.size()==0){
                RmlUtil.Tip.Alert(this,"mei");
            }
            else
                {
                RmlUtil.Dialog.List(
                        this,
                        "请选择您需要进行集合操作的图层",
                        fl2EditTitles,
                        null,
                        0,
                        new RmlUtil.Dialog.OnList() {
                            @Override
                            public void onConfirm(int select) {
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                    _toolbar.startActionMode(
                                            new RmlGeoEditAction(
                                                    DroneMapActv.this,
                                                    mv,
                                                    fl2Edit.get(select)),
                                            ActionMode.TYPE_FLOATING);
                                }else{
                                    _toolbar.startActionMode(
                                            new RmlGeoEditAction(
                                                    DroneMapActv.this,
                                                    mv,
                                                    fl2Edit.get(select)));
                                }
                            }

                            @Override
                            public void onCancel() {
                                RmlUtil.Tip.Toast("取消编辑");
                            }

                            @Override
                            public void onNeutral() {}
                        });
            }
        }else if (item.getItemId() == R.id.act_layers) {
            viewId = _layerList.getId();
        } else if (item.getItemId() == R.id.act_identity) {
            viewId = _featureInfo.getId();
            MapView mv = (MapView) _geoViewHolder.getGeoView();
            (mv).setOnTouchListener(new MapViewIdentityOnTouchListener(this, mv));
        }else if (item.getItemId() == R.id.act_task) {
            viewId = _tasklist.getId();

            _tasklist.setup(
                    this,
                    _mapLoader.getPrj().getEditMap(),
                    _mapLoader.getPrj().getOptionalMap().getLayers(),
                    _geoViewHolder,
                    null);
        }
        else if (item.getItemId() == R.id.act_free_draw) {
            MapView mv = (MapView) _geoViewHolder.getGeoView();

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                _toolbar.startActionMode(
                        new RmlFreeDrawAction(
                                this,
                                mv,
                                _mapLoader.getPrj().getEditMap().getFreeLineLayer())
                ,ActionMode.TYPE_FLOATING);
            }else{
                _toolbar.startActionMode(
                        new RmlFreeDrawAction(
                                this,
                                mv,
                                _mapLoader.getPrj().getEditMap().getFreeLineLayer()));
            }
        }
        else if (item.getItemId() == R.id.act_mark_draw) {
            MapView mv = (MapView) _geoViewHolder.getGeoView();
            FeatureLayer l = _mapLoader.getPrj().getEditMap().getMarkolygonLayer();

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                _toolbar.startActionMode(
                        new RmlMarkPolygonDrawAction(this,mv,l), ActionMode.TYPE_FLOATING);
            }else{
                _toolbar.startActionMode( new RmlMarkPolygonDrawAction(this,mv,l));
            }
        }

        _leftPanel.setOnSelect(viewId);
        _rightPanel.setOnSelect(viewId);

        return super.onOptionsItemSelected(item);
    }


    public static class StartInfo implements IRmlSerializable {
        public String prjName;

        public StartInfo(String name) {
            prjName = name;
        }
    }

    class MapViewIdentityOnTouchListener extends DefaultMapViewOnTouchListener {

        public MapViewIdentityOnTouchListener(Context context, MapView mapView) {
            super(context, mapView);
        }


        @Override
        public boolean onSingleTapConfirmed(MotionEvent e) {
            super.onSingleTapConfirmed(e);
            Point mp = mMapView.screenToLocation(new android.graphics.Point((int) e.getX(), (int) e.getY()));

            ArrayList<Layer>alllayers=new ArrayList<>();
            for(Layer l:_geoViewHolder.getRefrenceLayers()){
                if(l.isVisible())
                    alllayers.add(l);
            }
            for(Layer l:_geoViewHolder.getOperationalLayers()){
                if(l.isVisible())
                    alllayers.add(l);
            }
            new RmlFeatureLayerQueryHelper(alllayers, mp) {

                @Override
                public void onQueryResult(QueryResult[] queryResult) {
                    _featureInfo.setup(queryResult, 0);
                }

            };

            return super.onSingleTapConfirmed(e);
        }
    }
}
